package com.ruoyi.topInsectImg.controller;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.topInsectImg.domain.*;
import com.ruoyi.topInsectImg.service.OpenApiService;
import com.ruoyi.topInsectImg.utils.HttpClientUtils;
import com.ruoyi.topInsectImg.utils.TopInsect;
import com.ruoyi.topInsectImg.utils.soa.SOAResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 调用 Top API 获取虫情测报灯图片
 * 只调用一个设备，消去重复设备,注释代码做修改，insectImg 替换为 insectImgU
 *
 * @author Mr-Le
 */
@Api("获取虫情测报灯图片")
@Slf4j
@RestController
@RequestMapping("/insectImg")
public class OpenApiController {

    /**
     * 存储文件的路径
     */
    @Value("${ruoyi.profile}")
    private String profile;

    @Autowired
    private OpenApiService openApiService;

    @ApiOperation("获取虫情测报灯图片数据")
    @GetMapping("/get")
    public AjaxResult topInsectImg(String startDate, String endDate) {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("user_name", "wzyq");
        params.put("password", "1702a132e769a623c1adb78353fc9503");
        SOAResponse soaResponse = null;
        int num = 0;

        /* List 集合用来存放返回的数据 */
        Integer[] stationId = new Integer[10];
        List<Terminal> terminalList = new ArrayList<Terminal>();
        List<Device> deviceList = new ArrayList<Device>();
        List<InsectImg> insectImgList = new ArrayList<InsectImg>();

        /* Api接口封装 */
        TopInsect topInsect = new TopInsect();

        /* 1.登录，获取Token */
        while (soaResponse == null) {
            soaResponse = topInsect.topLogin(params);
        }
        params.put("user_token", soaResponse.getResult().get("user_token"));
        log.info("user_token:" + params.get("user_token"));
//        /* 2.获取基地列表 */
//        List<StationList> stationList = topInsect.getStationList(params);
//        for (int i = 0; i < stationList.size(); i++) {
//            stationId[i] = stationList.get(i).getStationId();
//        }
//
//        /* 3.获取基地下所有终端列表 */
//        for (Integer station : stationId) {
//            if (station != null) {
//                params.put("station_id", station);
//                List<Terminal> list = topInsect.getTerminal(params);
//                if (list.isEmpty()) {
//                    return AjaxResult.error("获取虫情测报灯基地列表出错，请重试！");
//                } else {
//                    terminalList.addAll(list);
//                }
//            }
//        }
//        System.out.println("获取终端设备列表成功!");
//
//        /* 4.获取所有终端下设备列表 */
//        for (Terminal terminal : terminalList) {
//            if (terminal != null) {
//                params.put("terminal_id", terminal.getTerminalId());
//                List<Device> device = topInsect.getDevice(params);
//                if (device.isEmpty()) {
//                    return AjaxResult.error("获取虫情测报灯基地下设备列表出错，请重试！");
//                } else {
//                    deviceList.addAll(device);
//                }
//            }
//        }
//        System.out.println("获取设备列表成功!");

        /* 5.根据设备获取图片列表 */
        params.put("start_date", startDate);
        params.put("end_date", endDate);
        params.put("record_count", 100);
//        for (Device device : deviceList) {
//            params.put("device_id", device.getDeviceId());
            params.put("device_id", 170471);
            List<InsectImg> insectImg = topInsect.getInsectImg(params);
            if (insectImg.isEmpty()) {
                return AjaxResult.error("获取图片列表为空，请更新开始结束时间重试！");
            } else {
//                insectImgList.addAll(insectImg);
                insectImgList = insectImg;
            }
//        }
        System.out.println("获取图片列表成功!");
        num = insectImgList.size();

//        for (InsectImg insectImg : insectImgList) {
        for (InsectImg insectImgU : insectImgList) {
            String path = profile + File.separator + "insectImg" + File.separator + insectImgU.getDeviceId();
            boolean b = downloadImage(insectImgU.getImgUrl(), path, insectImgU.getImageName());
            WebFrontEnd webFrontEnd = setWebFrontPram(insectImgU.getImgId(), insectImgU.getDeviceName(),
                    Constants.RESOURCE_PREFIX + "/" + "insectImg" + "/" + insectImgU.getDeviceId() + "/" + insectImgU.getImageName(),
                    insectImgU.getImageName(),
                    insectImgU.getDeviceId());
            openApiService.insertWebFrontEnd(webFrontEnd);
        }
        return AjaxResult.success("获取图片成功！", num);
    }

    /**
     * 查数据库得到此前下载的测报灯图片信息
     *
     * @param num 数量
     * @return 图片集合
     */
    @GetMapping("/select/{num}")
    public List<WebFrontEnd> getDownloadNum(@PathVariable(value = "num")int num){

//        String url = "http://localhost:8080/detection/model";
//        HashMap<String, Object> map = new HashMap<>();
//        File file = new File("D:\\0.服务器文件\\0.jpg");
//        map.put("Authorization", SecurityUtils.getAuthentication());
//        map.put("imageName", file);
//        String str = "";
        System.out.println("进来了");

        return null;

    }



    /**
     * 设置前端传入参数
     * @param id id
     * @param name 基地名
     * @param url 原始地址
     * @param imgName
     * @return
     */
    private WebFrontEnd setWebFrontPram(Integer id, String name, String url, String imgName, Integer deviceId){
        WebFrontEnd webFrontEnd = new WebFrontEnd();
        webFrontEnd.setImgId(id);
        webFrontEnd.setName(name);
        webFrontEnd.setUrl(url);
        webFrontEnd.setImageName(imgName);
        webFrontEnd.setDeviceId(deviceId);
        return webFrontEnd;
    }

    /**
     * 通过URL下载图片
     *
     * @param url      图片链接
     * @param dir      保存目录
     * @param fileName 保存文件名
     * @return 保存图片状态
     */
    private boolean downloadImage(String url, String dir, String fileName) {
        boolean image = false;
        try {
            File localFile = getAbsoluteFile(dir, fileName);
            image = HttpClientUtils.downloadImage(url, "JPEG", localFile);
        } catch (Exception e) {
            System.out.println(e);
        }
        return image;
    }

    /**
     * 获取文件，通过路径，没有文件就创建文件
     *
     * @param saveDir  保存路径
     * @param fileName 文件名
     * @return 返回文案类型
     * @throws IOException IO操作异常
     */
    private static final File getAbsoluteFile(String saveDir, String fileName) throws IOException {
        File desc = new File(saveDir + File.separator + fileName);

        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        if (!desc.exists()) {
            desc.createNewFile();
        }
        return desc;
    }


}
